import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { Box, CircularProgress, Alert } from '@mui/material';

import { useAuth } from '@/stores';
import { RouteGuard } from '@/types';
import { commonStyles } from '@/styles/utils';

interface ProtectedRouteProps {
  children: React.ReactNode;
  guard?: RouteGuard;
}

export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ 
  children, 
  guard = {} 
}) => {
  const location = useLocation();
  const { 
    isAuthenticated, 
    user, 
    hasPermission, 
    hasRole, 
    hasAnyPermission,
    hasAllPermissions,
    isLoading 
  } = useAuth();

  const {
    requireAuth = true,
    permissions = [],
    roles = [],
    redirect = '/login',
    onUnauthorized,
  } = guard;

  // 加载中状态
  if (isLoading) {
    return (
      <Box sx={commonStyles.flexCenter} minHeight="200px">
        <CircularProgress />
      </Box>
    );
  }

  // 检查认证状态
  if (requireAuth && !isAuthenticated) {
    // 在开发环境中，允许绕过认证直接访问登录页面
    if (import.meta.env.DEV && location.pathname === '/login') {
      return <>{children}</>;
    }
    return <Navigate to={redirect} state={{ from: location }} replace />;
  }

  // 在开发环境中简化权限检查
  if (import.meta.env.DEV) {
    return <>{children}</>;
  }

  // 检查用户权限
  if (permissions.length > 0) {
    const hasRequiredPermissions = hasAllPermissions(permissions);
    if (!hasRequiredPermissions) {
      if (onUnauthorized) {
        onUnauthorized();
        return null;
      }
      return (
        <Box sx={{ p: 3 }}>
          <Alert severity="error">
            抱歉，您没有访问此页面的权限
          </Alert>
        </Box>
      );
    }
  }

  // 检查用户角色
  if (roles.length > 0) {
    const hasRequiredRole = roles.some(role => hasRole(role));
    if (!hasRequiredRole) {
      if (onUnauthorized) {
        onUnauthorized();
        return null;
      }
      return (
        <Box sx={{ p: 3 }}>
          <Alert severity="error">
            抱歉，您没有访问此页面的角色权限
          </Alert>
        </Box>
      );
    }
  }

  return <>{children}</>;
};